package com.eduhzy.ttw.teacher.mvp.presenter;

import android.app.Application;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.PlatformNoticeData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.teacher.mvp.contract.PlatformNoticeContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-7-20 16:41:22
 */
@ActivityScope
public class PlatformNoticePresenter extends BasePresenter<PlatformNoticeContract.Model, PlatformNoticeContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private int page = 1;
    private int pageSize = 10;
    @Inject
    BaseQuickAdapter<PlatformNoticeData, AutoBaseViewHolder> mAdapter;


    @Inject
    public PlatformNoticePresenter(PlatformNoticeContract.Model model, PlatformNoticeContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }


    public void getSendMsgList(boolean pullToRefresh, int messageType) {
        if (pullToRefresh) {
            page = 1;
        } else {
            page++;
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("receiverId", SPUtils.getInstance().getString(Constants.USERID));
        map.put("messageType", messageType);
        map.put("pageNo", page);
        map.put("pageSize", pageSize);
        mModel.getSendMsgList(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    if (pullToRefresh)
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    if (pullToRefresh)
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<List<PlatformNoticeData>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<PlatformNoticeData>> data) {
                        if (data.isResult()) {
                            if (pullToRefresh) {
                                mAdapter.setNewData(data.getData());
                            } else {
                                mAdapter.addData(data.getData());
                            }
                            if (data.getData().size() < pageSize) {
                                mAdapter.loadMoreEnd(true);
                            } else {
                                mAdapter.loadMoreComplete();
                            }
                        } else {
                            if (ObjectUtils.isNotEmpty(data.getMessage())) {
                                mRootView.showMessage(data.getMessage());
                            }
                        }
                        if (ObjectUtils.isEmpty(data.getData()) && ObjectUtils.isEmpty(mAdapter.getData())) {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_data));
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (pullToRefresh) {
                            if (t instanceof ConnectException || t instanceof UnknownHostException) {
                                mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_network));
                            } else {
                                mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.load_error));
                            }
                        } else {
                            mAdapter.loadMoreFail();
                        }
                    }
                });
    }

    public void markRead(String inboxId) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("inboxIds", inboxId);
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        mModel.markRead(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        if (commonData.isResult()) {
                        }
                    }
                });
    }
}
